// miniprogram/pages/deital/deital.js
import {
  getSolitaireById
} from './../../api/solitaire.js'
import {
  isSignUp,
  loadSolitaireInfo,
  cancelSignUp
} from './../../api/solitaire_info'
const dayjs = require('dayjs')
Page({

  /**
   * 页面的初始数据
   */
  data: {},
  onLoad(options) {
    console.log("options", options)
    this.data._id = options._id

  },
  onShow() {
    const _id = this.data._id
    wx.showLoading({
      title: '请稍等...',
    })
    Promise.all([getSolitaireById(_id), isSignUp(_id), loadSolitaireInfo(0, 20,_id)]).then(res => {
      console.log("res", res)
      const item = res[0].result.list[0] //发起人信息
      const isSignUp = res[1].result.total > 0 //是否报名
      const list = this.transformSolitaireInfo(res[2].result.list)
      this.setData({
        info: {
          head: item.user.avatarUrl, //头像
          name: item.user.nickName, //发起人
          time: dayjs(item.date).format('YYYY-MM-DD HH:mm'), //时间
          typeName: item.activity.name,
          typeColor: item.activity.color,
          title: item.title,
          desc: item.remarks,
          num: item.num, //人数
          btn: "./../../images/btn-edit.png", //编辑
          isShowBtn: item.user.isSelf,
          isIndex: false,
        },
        isSignUp: isSignUp,
        list: list
      })
      wx.hideLoading()
    })
  },
  //转换参与者信息
  transformSolitaireInfo(res) {
    return res.map(info => {
      return {
        nickName: info.user.nickName,
        avatarUrl: info.user.avatarUrl,
        date: dayjs(info.date).format('YYYY-MM-DD HH:mm'),
        name: info.name,
        tel: info.tel,
        desc: info.desc,
        imgUrls: info.imgUrls
      }
    })
  },
  //分享
  onShareAppMessage(obj) {
    console.log(obj)
  },
  handlerSigUp() {
    const _id = this.data._id
    const title = this.data.info.title
    const act = this.data.info.typeName
    if (this.data.isSignUp) {
      wx.showModal({
        title: "提示",
        content: "是否取消报名?"
      }).then(res => {
        if (res.confirm) {
          wx.showLoading({
            title: '取消中...',
          })
          cancelSignUp(_id)
            .then(res => {
              console.log("取消报名",res)
             return loadSolitaireInfo(0, 20)
            })
            .then(res => {
              console.log("res", res)
              wx.hideLoading()
              wx.showToast({
                title: '报名已取消',
              })
              const list = this.transformSolitaireInfo(res.result.list)
              this.setData({
                list: list,
                isSignUp: false
              })

            })
        }
      })
      //取消报名

    } else {
      //报名
      wx.navigateTo({
        url: './../register/register?_id=' + _id + '&act=' + act + '&title=' + title,
      })
    }
  }
})